package org.acghub.config.generator;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import lombok.extern.slf4j.Slf4j;
import org.acghub.config.*;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/24/星期四 12:33
 * @Version 1.0
 */
@Slf4j
public class FreeMarkerCodeGenerator implements CodeGenerator {

    private Template template;

    private boolean useLombok;

    @Override
    public void init() throws Exception {
        final String encoding = TableConfig.get(TableConfig.ConfigKeyEnum.ENCODING, "UTF-8");
        final Version version = TableConfig.get(TableConfig.ConfigKeyEnum.FREEMARKER_VERSION, Configuration.VERSION_2_3_32);
        final String templateName = TableConfig.get(TableConfig.ConfigKeyEnum.FREEMARKER_TEMPLATE_NAME, "ConfigTemplate.ftl");
        useLombok = TableConfig.get(TableConfig.ConfigKeyEnum.CODE_GENERATE_USE_LOMBOK, false);
        final Configuration cfg = new Configuration(version);
        final String templateDir = TableConfig.get(TableConfig.ConfigKeyEnum.FREEMARKER_TEMPLATE_DIR, "templates");
        if (TableConfig.has(TableConfig.ConfigKeyEnum.FREEMARKER_TEMPLATE_DIR)){
            cfg.setDirectoryForTemplateLoading(new File(templateDir));
        }else {
            cfg.setClassLoaderForTemplateLoading(getClass().getClassLoader(), templateDir);
        }
        cfg.setDefaultEncoding(encoding);
        template = cfg.getTemplate(templateName, encoding);
    }

    @Override
    public void generate(String outputDir, TableMeta meta) {
        final String packageName = meta.getPackageName();
        final String className = meta.getTableName();
        final List<TableField> fields = meta.getHeader().getFields();

        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("packageName", packageName);
        dataModel.put("className", className);
        dataModel.put("fields", fields);
        dataModel.put("idType", meta.getIdType());
        dataModel.put("superClass", AbstractConf.class.getName());
        dataModel.put("useLomBok", useLombok);

        String packagePath = packageName.replace(".", "/");
        File dir = new File(outputDir, packagePath);
        dir.mkdirs();

        File javaFile = new File(dir, className + ".java");
        try (Writer writer = new FileWriter(javaFile)) {
            template.process(dataModel, writer);
        } catch (Exception e) {
            log.error("生成Java文件失败：{}", javaFile.getAbsolutePath(), e);
        }
        log.info("✅ Java 文件生成成功：{}", javaFile.getAbsolutePath());
    }

    @Override
    public void exit() {
        template = null;
        log.info("✅ {} exit", getClass().getSimpleName());
    }
}
